package com.ctsi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.core.common.enums.StatusType;
import com.ctsi.core.common.exception.MarsException;
import com.ctsi.core.common.util.$;
import com.ctsi.core.database.util.PageUtil;
import com.ctsi.core.web.enums.AdminTypeEnum;
import com.ctsi.core.web.enums.YesOrNotEnum;
import com.ctsi.system.constant.DictConstant;
import com.ctsi.system.constant.SysConstant;
import com.ctsi.system.entity.App;
import com.ctsi.system.mapper.AppMapper;
import com.ctsi.system.service.IAppService;
import com.ctsi.system.service.IMenuService;
import com.ctsi.system.service.IUserService;
import com.ctsi.uaa.enums.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统应用表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements IAppService {

	@Autowired
	private IUserService userService;
    @Autowired
	private IMenuService menuService;

	@Override
	public IPage<App> listPage(Search search) {
		boolean isKeyword = $.isNotNull(search.getKeyword());
		LambdaQueryWrapper<App> queryWrapper = Wrappers.<App>query().lambda()
				// 根据名称查询
				.like(isKeyword, App::getName, search.getKeyword())
				.or(isKeyword)
				// 根据惟一编码查询
				.like(isKeyword, App::getCode, search.getKeyword())
				.orderByAsc(App::getId);
		return this.baseMapper.selectPage(PageUtil.getPage(search), queryWrapper);
	}

	@Override
	public List<Dict> getLoginApps(Long userId,Integer userType) {
		List<Dict> userAppDictList = CollectionUtil.newArrayList();

		LambdaQueryWrapper<App> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(App::getStatus, StatusType.ENABLE.getCode());
		Integer adminType;
		switch (UserType.valueOf(userType)){
			case SYSTEM:
				adminType = userService.getById(userId).getAdminType();
				break;
			case TELECOM:
				adminType = AdminTypeEnum.NONE.getCode();
				break;
			default:
				throw new MarsException(SysConstant.NOT_SUPPORT_USERTYPE);
		}

		// 如果不是超级管理员则有自己的菜单对应的应用编码
		if (!$.equals(AdminTypeEnum.SUPER_ADMIN.getCode(), adminType)) {
			// 获取用户菜单对应的应用编码集合
			List<String> appCodeList = menuService.getUserMenuAppCodeList(userId, userType);
			//　当应用编码不为空时，则限制查询范围
			if ($.isNotEmpty(appCodeList)) {
				queryWrapper.in(App::getCode, appCodeList);
			} else {
				//没查到应用编码则直接返回
				return userAppDictList;
			}
		}

		// 定义是否有默认激活的应用标志
		AtomicBoolean hasDefaultActive = new AtomicBoolean(false);
		// 遍历
		this.list(queryWrapper).forEach(app -> {
			Dict dict = Dict.create();
			dict.put(DictConstant.CODE, app.getCode());
			dict.put(DictConstant.NAME, app.getName());
			dict.put(DictConstant.ICON, app.getIcon());
			//如果有默认激活的
			if (YesOrNotEnum.Y.getCode().equals(app.getActive())) {
				hasDefaultActive.set(true);
				dict.put("active", true);
				//将其放在第一个
				userAppDictList.add(0, dict);
			} else {
				dict.put("active", false);
				userAppDictList.add(dict);
			}
		});
		if ($.isNotEmpty(userAppDictList)) {
			//如果默认激活的系统没有，则第一个为默认激活的系统
			if (!hasDefaultActive.get()) {
				Dict dict = userAppDictList.get(0);
				dict.put("active", true);
			}
		}
		return userAppDictList;
	}

	@Override
	public boolean setDefault(App app) {
		// 获取已激活的ID
		List<Long> longs = this.list(Wrappers.<App>lambdaQuery()
				.eq(App::getStatus, StatusType.ENABLE.getCode())
				.eq(App::getActive, YesOrNotEnum.Y.getCode()))
				.stream().map(App::getId).collect(Collectors.toList());
		// 全部更新为非默认
		this.update(Wrappers.<App>lambdaUpdate().set(App::getActive, YesOrNotEnum.N.getCode()).in(App::getId, longs));
		// 更新为默认应用
		return this.update(Wrappers.<App>lambdaUpdate()
				.set(App::getActive, YesOrNotEnum.Y.getCode()).eq(App::getId, app.getId()));
	}
}
